package com.eagledata.common.utils;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.tomcat.util.http.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.springframework.web.multipart.MultipartFile;

import com.eagledata.common.exception.file.FileNameLengthLimitExceededException;
import com.eagledata.framework.config.EagleDataConfig;

/**
 * 文件上传工具类
 * 
 * @author ruoyi
 */
public class FileUploadUtils {

	// 默认大小 50M
	public static final long DEFAULT_MAX_SIZE = 52428800;

	// 默认上传的地址
	private static String defaultBaseDir = EagleDataConfig.getProfile();

	// 默认的文件名最大长度
	public static final int DEFAULT_FILE_NAME_LENGTH = 200;

	// 默认文件类型jpg
	public static final String IMAGE_JPG_EXTENSION = ".jpg";

	private static int counter = 0;

	public static void setDefaultBaseDir(String defaultBaseDir) {
		FileUploadUtils.defaultBaseDir = defaultBaseDir;
	}

	public static String getDefaultBaseDir() {
		return defaultBaseDir;
	}

	/**
	 * 获取文件后缀名
	 * @param fileName
	 * @return
	 */
	public static String getFileSuffix(String fileName) {
		try {
			String suffix = fileName.substring(fileName.lastIndexOf("."));
			return suffix;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 以默认配置进行文件上传
	 *
	 * @param file
	 *            上传的文件
	 * @return 文件名称
	 * @throws Exception
	 */
	public static final String upload(MultipartFile file) throws IOException {
		try {
			return upload(getDefaultBaseDir(), file, FileUploadUtils.IMAGE_JPG_EXTENSION);
		} catch (Exception e) {
			throw new IOException(e);
		}
	}

	/**
	 * 根据文件路径上传
	 *
	 * @param baseDir
	 *            相对应用的基目录
	 * @param file
	 *            上传的文件
	 * @return 文件名称
	 * @throws IOException
	 */
	public static final String upload(String baseDir, MultipartFile file) throws IOException {
		try {
			return upload(baseDir, file, FileUploadUtils.IMAGE_JPG_EXTENSION);
		} catch (Exception e) {
			throw new IOException(e);
		}
	}

	/**
	 * 文件上传
	 *
	 * @param baseDir
	 *            相对应用的基目录
	 * @param file
	 *            上传的文件
	 * @param needDatePathAndRandomName
	 *            是否需要日期目录和随机文件名前缀
	 * @param extension
	 *            上传文件类型
	 * @return 返回上传成功的文件名
	 * @throws FileSizeLimitExceededException
	 *             如果超出最大大小
	 * @throws FileNameLengthLimitExceededException
	 *             文件名太长
	 * @throws IOException
	 *             比如读写文件出错时
	 */
	public static final String upload(String baseDir, MultipartFile file, String extension)
			throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException {

		int fileNamelength = file.getOriginalFilename().length();
		if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
			throw new FileNameLengthLimitExceededException(file.getOriginalFilename(), fileNamelength,
					FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
		}

		assertAllowed(file);

		//String fileName = encodingFilename(file.getOriginalFilename(), extension);
		String fileName = encodingFilename(extension);
		
		File desc = getAbsoluteFile(baseDir, baseDir + fileName);
		file.transferTo(desc);
		return fileName;
	}

	private static final File getAbsoluteFile(String uploadDir, String filename) throws IOException {
		File desc = new File(File.separator + filename);

		if (!desc.getParentFile().exists()) {
			desc.getParentFile().mkdirs();
		}
		if (!desc.exists()) {
			desc.createNewFile();
		}
		return desc;
	}

	/**
	 * 编码文件名
	 */
	@SuppressWarnings("unused")
	private static final String encodingFilename(String filename, String extension) {
		
		filename = filename.replace("_", " ");
		filename = new Md5Hash(filename + System.nanoTime() + counter++).toHex().toString() + extension;
		return filename;
	}
	
	/**
	 * 时间戳格式文件名称
	 * @param extension
	 * @return
	 */
	private static final String encodingFilename(String extension) {
		Random random=new Random();
		int i = random.nextInt(100);
		String filename = StringUtils.join(DateUtils.timeStamp(), String.valueOf(i), extension);
		return filename;
	}

	/**
	 * 文件大小校验
	 *
	 * @param file
	 *            上传的文件
	 * @return
	 * @throws FileSizeLimitExceededException
	 *             如果超出最大大小
	 */
	public static final void assertAllowed(MultipartFile file) throws FileSizeLimitExceededException {
		long size = file.getSize();
		if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE) {
			throw new FileSizeLimitExceededException("not allowed upload upload", size, DEFAULT_MAX_SIZE);
		}
	}
	
	public static String uploadImage(HttpServletRequest request,String path_deposit,MultipartFile file,boolean isRandomName) {
        //上传
        try {
            String[] typeImg={"gif","png","jpg"};

            if(file!=null){
                String origName=file.getOriginalFilename();// 文件原名称
                System.out.println("上传的文件原名称:"+origName);
                // 判断文件类型
                String type=origName.indexOf(".")!=-1?origName.substring(origName.lastIndexOf(".")+1, origName.length()):null;
                if (type!=null) {
                    boolean booIsType=false;
                    for (int i = 0; i < typeImg.length; i++) {
                        if (typeImg[i].equals(type.toLowerCase())) {
                            booIsType=true;
                        }
                    }
                    //类型正确
                    if (booIsType) {
                        //存放图片文件的路径
                        String path=request.getSession().getServletContext().getRealPath(path_deposit);
                        //组合名称
                        String fileSrc=""; 
                        //是否随机名称
                        if(isRandomName){
                            origName=DateUtils.parseDateToStr("yyyy-MM-dd", new Date())+UUID.randomUUID().toString()+origName.substring(origName.lastIndexOf("."));
                        }
                        //判断是否存在目录
                        File targetFile=new File(path,origName);
                        if(!targetFile.exists()){
                            targetFile.mkdirs();//创建目录
                        }
                        //上传
                        file.transferTo(targetFile);
                        //完整路径
                        fileSrc=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+path_deposit+origName;
                        System.out.println("图片上传成功:"+fileSrc);
                        return fileSrc;
                    }
                }
            }
            return null;
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
